package com.windchimes.edueval_platform.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 全局异常处理器
 * 拦截所有带有 @RestController 和 @Controller 的类
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {

//    /**
//     * 处理数据库唯一约束冲突异常
//     */
//    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
//    public R<String> handleDuplicateEntry(SQLIntegrityConstraintViolationException ex) {
//        log.error("数据库唯一约束冲突: {}", ex.getMessage());
//
//        if (ex.getMessage().contains("Duplicate entry")) {
//            String[] split = ex.getMessage().split(" ");
//            String duplicateValue = split[2].replace("'", ""); // 去除引号
//            return R.error(duplicateValue + "已存在");
//        }
//        return R.error("数据库操作失败");
//    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handleDuplicateEntry(SQLIntegrityConstraintViolationException ex) {
        log.error("数据库唯一约束冲突: {}", ex.getMessage());

        // 使用正则提取关键信息
        Pattern entryPattern = Pattern.compile("Duplicate entry '(.*?)'");
        Pattern keyPattern = Pattern.compile("for key '(.*?)'");

        String value = "";
        String constraint = "";

        Matcher entryMatcher = entryPattern.matcher(ex.getMessage());
        if(entryMatcher.find()) value = entryMatcher.group(1);

        Matcher keyMatcher = keyPattern.matcher(ex.getMessage());
        if(keyMatcher.find()) constraint = keyMatcher.group(1);

        // 根据约束名称返回友好提示
        switch(constraint) {
            case "uk_phone":
                return R.error("手机号"+value+"已注册");
            case "uk_student_course":
                return R.error("该学生已加入本课程");
            case "uk_name_course":
                return R.error("同名考核类型已存在");
            default:
                return R.error("数据冲突：" + value);
        }
    }
    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(CustomException.class)
    public R<String> handleBusinessException(CustomException ex) {
        log.error("业务异常: {}", ex.getMessage());
        return R.error(ex.getMessage());
    }

    /**
     * 处理其他未捕获异常（可选）
     */
    @ExceptionHandler(Exception.class)
    public R<String> handleUnexpectedException(Exception ex) {
        log.error("系统异常: {}", ex.getMessage(), ex); // 打印堆栈
        return R.error("系统繁忙，请稍后重试");
    }
}